package com.filters;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.common.models.RetCode;
import com.common.models.RetResult;
import com.common.util.PublicUtil;
import com.google.gson.Gson;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

@Component
public class WatchDogFilter extends ZuulFilter{

    private static Logger log = LoggerFactory.getLogger(WatchDogFilter.class);
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
    	
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        
    	//首先看看是否是get请求，如果是，就不用转发了
    	if(request.getMethod().equals("GET"))
    	{
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(405);
            
            return null;
    	}
    	

        log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        
        //验证时间戳。请求时间在10分钟以内的算有效请求
        RetResult ret = new RetResult();
        String timestamp = request.getParameter("timestamp");
        
        if(timestamp == null || timestamp.equals("")) {
        	ret.setCode(RetCode.TIMESTAMP_ERROR);
        	ret.setMsg(RetCode.TIMESTAMP_ERROR_MSG);
        }
        
        //计算时间差，判断是否是有效请求
        //有效请求为距当前时间10分钟之内的请求
        Long lst = Long.parseLong(timestamp);
        Long s = (System.currentTimeMillis() - lst) / 1000;
        Long validTime = (long) (10 * 60);
        if(s > validTime)
        {
        	ret.setCode(RetCode.TIMESTAMP_ERROR);
        	ret.setMsg(RetCode.TIMESTAMP_ERROR_MSG);
        }
        
        if(ret.getCode() == RetCode.TIMESTAMP_ERROR)
        {
        	Gson gson = new Gson();
        	String jsonStr = gson.toJson(ret);
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(405);
            
            try {
            	HttpServletResponse response = ctx.getResponse();
            	response.setCharacterEncoding("UTF-8");
            	//jsonStr = PublicUtil.getUTF8String(jsonStr);
                //ctx.getResponse().getWriter().write(jsonStr);
            	ctx.setResponseBody(jsonStr);
            }catch (Exception e){
            	e.printStackTrace();
            }

            return null;
        }
        
        log.info("ok");
        return null;
    }
}